import React, { Component } from 'react';
import { 
	// Button,
	// Col,
	// DatePicker,
	Form,
	Input,
	// message,
	Modal, 
	// Radio,
	// Row,
	Typography,
	Select,
	Tag,
	Table
} from 'antd';
import styles from './index.module.scss';
import TextInput from 'react-autocomplete-input';
import './index.css';
import {
	calculateField, checkFormula,
	resetCalculateField,
	getOperators
	// checkFormula
} from 'src/services/DataManage';
import { FormInstance } from 'antd/lib/form';

const OptionSelect = props => {

	const [ st,setSt ] = React.useState( 'all' );
	const [ rowId,setRowId ] = React.useState( 1 );
	const [ dataSource,setDataSource ] = React.useState( [] );
	const [ columns,setColumns ] = React.useState( [] );

	const handleRow = ( record, index ) => {
		setRowId( record.key );
		// eslint-disable-next-line react/prop-types
		props.setInfo( record );

	};

	React.useEffect( () => {
		getOperators( { data: {} } ).then( info => {
			if( info.data&&info.data.success ) {
				let rdata = info.data.data.map( item => {item['key'] = item['operator']; return item;} );
				setDataSource( rdata );
			}
		} );
	    setColumns( [
			{
				title: '姓名',
				dataIndex: 'operator',
				key: 'operator',
				align: 'center'
			},
		] );
	}, [] );


	React.useEffect( () => {
		if( dataSource.length > 0 && rowId === 1 ) {
			handleRow( dataSource[0],0 );
		}
	} );


	const selectChange = value => {
		setSt( value );
	};

	
	const setRowClass = ( record,index ) => {
		return  rowId === record.key?`${styles.clickRowStyl}`:null;
	};

	return (
		<div>
			<div>
                解释
			</div>
			<div style={{ marginBottom: '10px' }}>
				<Select size={'middle'} style={{ width: '100%' }}
					defaultValue={st} 
					onChange={selectChange}>
					<Select.Option value={'all'}>
                        全部
					</Select.Option>
				</Select>
			</div>
			<div>
				<Input size={'small'} placeholder={'请输入内容'}/>
			    <Table  columns={columns}
					bordered
					pagination={false}
					showHeader={false}
					size={'small'}
					rowClassName={setRowClass}
					onRow={( record, index ) =>  {
						return {
							onClick: event => {handleRow( record,index );}, // 点击行
							onDoubleClick: event => {},
							onContextMenu: event => {},
							onMouseEnter: event => {}, // 鼠标移入行
							onMouseLeave: event => {},
						};
					}}
					scroll={{ y: '300px' }}
					dataSource={dataSource}/>
			</div>
            
		</div>
	);
};


interface Iprops {
	modalVisibleValue:boolean
	FieldData:any
	modalVisible:any
	joinComponentFunc:any
	setOutDataFunc:any
}


class ComputedField extends Component<Iprops,any> {

	state = {
		info: {
			name: undefined,
			desc: undefined,
			examples: []

		},
		options: [],
		msg: '',
	}

	formRef = React.createRef<FormInstance>();
	
	setInfo = data => {
		this.setState( { info: { ...data } } );
	}
	
	handleCheck = async v => {
		//正则校验$符号前后的干扰数字
		let n = v.replace( /\s*/g,'' )
			.search( /(\}\d+|\d+\$|\d+\(|\)\d+|\d\[|\]\d+)/g );
		//校验不正常字符
		let m = v.replace( /\s*/g,'' )
			.search( /(\}\}|\$\{\{)/g );
		if( n !== -1 ) {
			this.setState( { msg: '有无效数字' } );
			return false;
		}
		if( m !== -1 ) {
			this.setState( { msg: '计算公式中包含错误，请仔细检查，比如“”‘；{}（）等连接符' } );
			return false;
		}
		let sdata = {
			'componentId': this.props.FieldData.id,
			'formula': v,
			'modelId': this.props.FieldData.modelId
		};
		const info = await checkFormula( { data: { ...sdata } } );
		if( info.data && info.data.success ) {
			return true;
		}else {
			this.setState( { msg: info.message } );
			return false;
		}
	}
	
	handleformula = value => {
		let a = value.replace( /\s*/g,'' );
		this.props.FieldData.model.fieldMappings.forEach( item => {
			let tmp = `{${item.finalFieldDesc}}`.replace( /\s*/g,'' );
			a = a.replace( RegExp( tmp, 'g' ), `{${item.tempFieldName}}`, ); //可以替換全部
		} );
		return a;
	}

	handleOk = async () => {
		this.formRef.current.validateFields().then( async value => {
			let { name,formula } = value;
			const fu = this.handleformula( formula );
			const rs = await this.handleCheck( fu );
			if( rs ) {
				let fields = {
					'formula': fu,
					'name': name
				};
				let info = null;
				//编辑修改
				if( this.props.FieldData.edit ) {
					const { code,name } = this.props.FieldData;
					info = await resetCalculateField( { data: { componentCode: code,componentName: name,'position': 1 ,fields } } );
				}else {
					info = await calculateField( { data: { modelId: this.props.FieldData.modelId,position: 1,fields } } );
				}
				if( info.data && info.data.success ) {
					const data =  info.data.data;
					let toData = { ...data,
						form: value,
						edit: this.props.FieldData.edit,
						nodeType: 'ComputedField',
						style: { 'primaryColor': '#0066FF' },
						shape: 'SimplicityNode' };
					this.props.joinComponentFunc( this.props.FieldData,toData,{} );
					this.handleCancel();
				}
			}
		} );
	}
	
	handleCancel = () => {
		this.formRef.current.resetFields();
		//执行数据清理工作
		let data = this.props.FieldData;
		delete data.edit;
		this.props.setOutDataFunc( data );
		this.setState( { msg: '' } );
		this.props.modalVisible( 'fieldComputedVisible',false );
	}



	//键盘事件
	inputKeyUp = ( e ) => {
	}
	
	
	componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<any>, snapshot?: any ): void {
		if( this.props.modalVisibleValue!== prevProps.modalVisibleValue ) {
			let names = this.props.FieldData.model.fieldMappings.map( item => `{${item.finalFieldDesc}}` );
			this.setState( { options: names } );
		}
		if( this.props.modalVisibleValue!== prevProps.modalVisibleValue && this.props.FieldData.form &&this.props.FieldData.edit ) {
			this.formRef.current.setFieldsValue( this.props.FieldData.form );
		}
	}


	render() {
	 	let title = '编辑计算';
	 	if( this.props.FieldData.edit ) {
	 		title += ' (编辑)';
	 	}
	 	return (
	 		<Modal title={title}
	 			okText={'确定'}
	 			width={1000}
	 			onOk={this.handleOk}
	 			onCancel={this.handleCancel }
	 			cancelText={'取消'}
	 			forceRender={false}
				   mask={false}
				   maskClosable={false}
				   // visible={true}
				visible={this.props.modalVisibleValue}
	 		>
	 			<div className={styles.content}>
	 				<div className={styles.work}>
	 					<div>
                            计算字段名称 
	 					</div>
						<Form ref={this.formRef}>
							<div className={styles.workName}>
								<Form.Item name={'name'}
										   rules={[ { required: true, message: '请输入计算字段名称' } ]}>
									<Input placeholder={'请输入计算字段名称 '} />
								</Form.Item>
							</div>
							<div className={styles.inputContent}>
								<Form.Item name={'formula'} rules={[ { required: true, message: '请输入表达式' } ]} >
									<TextInput spellcheck="false" maxOptions={0}  trigger={'$'} matchAny={true} offsetX={10} offsetY={10}
											   regex={'^[{}a-zA-Z0-9\\-_\u4e00-\u9fa5]+$'}
										   style={{ width: '100%',height: '300px' }} className={styles.input}
										   options={this.state.options } onKeyUp={this.inputKeyUp} />
								</Form.Item>
							</div>
						</Form>
	 					<div className={styles.workInfo}>
							{/*计算无效*/}
							{this.state.msg ?<Tag color="#f50">{this.state.msg}</Tag> :null}
	 					</div>
	 				</div>
	 				<div className={styles.option}>
	 					<OptionSelect setInfo={this.setInfo} />
	 				</div>
	 				<div className={styles.info}>
	 					<Typography.Title level={4}>{this.state.info.name}</Typography.Title>
	 					<Typography.Paragraph>{this.state.info.desc}</Typography.Paragraph>
						{
							this.state.info.examples.map( ( item,index ) =>
								( <Typography.Paragraph key={index}>{item}</Typography.Paragraph> )
							) 
						}
						
	 				</div>
	 			</div>
	 		</Modal>
	 	);
	 }
}

export default ComputedField;